/**
 * CustomerServlet
 * Servlet for an Ecom customer.
 * @author    Fabienne Boyer - Didier Donsez - may 2006
 */

package ecom.servlets;


import ecom.beans.account.AccountEntity;
import ecom.beans.account.AccountEntityFacadeRemote;
import ecom.beans.address.AddressEntity;
import ecom.beans.address.AddressEntityFacade;
import ecom.beans.address.AddressEntityFacadeRemote;
import ecom.beans.cart.CartSessionRemote;
import ecom.beans.customer.CustomerEntity;
import ecom.beans.customer.CustomerEntityFacade;
import ecom.beans.customer.CustomerEntityFacadeRemote;
import ecom.beans.dish.DishEntityFacadeRemote;
import ecom.beans.menuorder.MenuOrderEntityFacadeRemote;
import ecom.beans.store.StoreEntityFacadeRemote;
import ecom.client.Tx;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;




public class CustomerServlet extends HttpServlet {

    private static final long serialVersionUID = 6893863749912962928L;
   
    private Context initialContext;
    private UserTransaction utx;
	private DishEntityFacadeRemote dishEntityFacade;
    private AccountEntityFacadeRemote accountEntityFacade;
    private CustomerEntityFacadeRemote customerEntityFacade;
    private StoreEntityFacadeRemote storeEntityFacade;
	private AddressEntityFacadeRemote addressEntityFacade;
	private CartSessionRemote cartSessionBean;
	private MenuOrderEntityFacadeRemote menuOrderEntityFacade;

	public int readCustomer( PrintWriter out , int numChamp){
 	  
 	   out.println("Entrez les informations vous concernant :<br>");
 	   out.println("Prenom &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
 	   out.println("Nom &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
       out.println("Telephone &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\">(chiffres uniquement)<br>");
       out.println("E-mail &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
       out.println("Mot de passe &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\">(lettres, chiffres, tirets)<br>");
            
       return numChamp;
    }
     
	private int readAddress( PrintWriter out , int numChamp ) {
		out.println("Entrez les informations concernant l'adresse du client :<br>");
		out.println("Numero de la rue &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
        out.println("Nom de la rue &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
        out.println("Code postal &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
        out.println("Ville &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
        out.println("<input type=\"radio\" name=\"type_residence\" value=\"maison\" checked> &nbsp; MAISON |");
        //si appartement afficher ca!! utiliser javascript ici
        out.println("<input type=\"radio\" name=\"type_residence\" value=\"appartement\"> &nbsp; APPARTEMENT<br>");
        out.println("Numero du batiment &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
      	out.println("Numero de l'etage &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
      	out.println("Numero de l'appartement &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
         
      	return numChamp;
     }
	
	private int readAccount(PrintWriter out,  int numChamp){
		out.println("Entrez les informations concernant le compte bancaire du client :<br>");
        out.println("IBAN du compte &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\">(FRxxx...)<br>");
        return numChamp;
	}
	
		
	/*public CustomerEntity registerCustomer(
            String password,
            String email,
            String firstname, 
            String lastname,
            String tel,
            AddressEntity address,
            AccountEntity account
    ) {

			CustomerEntity newCustomer = new CustomerEntity();

            newCustomer.setPassword(password);
            newCustomer.setEmail(email);
            newCustomer.setFirstname(firstname);
            newCustomer.setLastname(lastname);
            newCustomer.setTel(tel);
            newCustomer.setCustomerAddress(address);
            newCustomer.setCustomerAccount(account);
            
            return newCustomer;

        }
*/
	
	private AddressEntity registerAddress(  String streetNum ,
							    String streetName,
								String zipcode,
								String city,
								String buildingNum,
								String floorNum,
								String apartmentNum,
								String type_residence,
								int addressType){ //addressType = 1 for a customer, 2 for a restaurant //Type_residence = "appartement" or "maison"
		AddressEntity address = new AddressEntity();
        address.setAddressType(addressType);
        address.setStreetNum(Integer.parseInt(streetNum));
	    address.setStreetName(streetName);
	    address.setZipcode(zipcode);
	    address.setCity(city);
	    if(type_residence=="appartement"){
	    	 address.setBuildingNum(Integer.parseInt(buildingNum));
	    	 address.setFloorNum(Integer.parseInt(floorNum));
	    	 address.setApartmentNum(Integer.parseInt(apartmentNum));
	    }
	    else{ 
	    	if (type_residence=="maison"){
	    		address.setBuildingNum(-1);
	            address.setFloorNum(-1);
	            address.setApartmentNum(-1);
	    	}
		}

	return address;
	
	}
	public AccountEntity registerAccount(int accountType , String iban, AccountEntityFacadeRemote accountEntityFacade ){
		AccountEntity account;
		account = accountEntityFacade.getAccountByAccountIBAN(iban);//pour verifer s il existe pas deja ce compte dans la base
		if(account == null) {
			account = new AccountEntity();
			account.setAccountType(accountType);
			account.setAccountIBAN(iban);
		}
			return account;
	}
	
	
	
	public void customerMenu(PrintWriter out){
		out.println("<p class='menubar'><a href=''>Nouveau compte client</a>&nbsp;|&nbsp;" +
										"<a href=''>S'identifier</a></a>&nbsp;|&nbsp;" +
										"<a href=''>Liste des plas</a>&nbsp;|&nbsp;" +
										"<a href=''>Sortir</a><br>");
	
	}
	
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
	
		int  numChamp = 0; // pour definir les nom des champs en ogmantant a chaque fois.
		
    	initialContext = null;
        utx = null;
        dishEntityFacade = null;
        accountEntityFacade = null;
        customerEntityFacade = null;
        storeEntityFacade = null;
		addressEntityFacade = null;
		cartSessionBean = null;
		menuOrderEntityFacade = null;
    	   	
    	 response.setContentType("text/html");
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         //out.println("<link type=\"text/css\" href=\"../ow_jonas.css\" rel=\"stylesheet\" id=\"stylesheet\">");
         out.println("<link rel=\"stylesheet\" href=\"style.css\" />");
         out.println("<title>");
         out.println("Customer Servlet</title>");
         out.println("</head>");
         out.println("<body style=\"background : white; color : black;\">");
      	
         System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory");
        
         try
         {
        	 initialContext = new InitialContext();
        	 //out.println("Creation of initialContext...OK   ");
         } 
         catch (Exception e)
         {
            System.err.println("Cannot get initial context for JNDI: " + e);
            System.exit(2);
         }

        try
        {
            utx = (UserTransaction) initialContext.lookup("javax.transaction.UserTransaction");
            //out.println("Creation of utx...OK   ");
        }
        catch (NamingException e) 
        {
            out.println("Cannot lookup UserTransaction: " + e);
            System.exit(2);
        }

		try
		{
            dishEntityFacade = (DishEntityFacadeRemote) initialContext.lookup("ecom.beans.dish.DishEntityFacade" + "_" + DishEntityFacadeRemote.class.getName() + "@Remote");
            //out.println("Creation of dishEntityFacade...OK   ");
        }
		catch (NamingException e) 
		{
            out.println("Cannot get dishEntityFacade : " + e);
            System.exit(2);
        }

        try
        {
            storeEntityFacade = (StoreEntityFacadeRemote) initialContext.lookup("ecom.beans.store.StoreEntityFacade" + "_" + StoreEntityFacadeRemote.class.getName() + "@Remote");
            //out.println("Creation of storeEntityFacade...OK    ");
        }
        catch (NamingException e)
        {
            out.println("Cannot get storeEntityFacade : " + e);
            System.exit(2);
        }

        try
        {
            customerEntityFacade = (CustomerEntityFacadeRemote) initialContext.lookup("ecom.beans.customer.CustomerEntityFacade" + "_" + CustomerEntityFacadeRemote.class.getName() + "@Remote");
            //out.println("Creation of customerEntityFacade...OK     ");
        } 
        catch (NamingException e)
        {
            out.println("Cannot get customerEntityFacade : " + e);
            System.exit(2);
        }

        try
        {
            accountEntityFacade = (AccountEntityFacadeRemote) initialContext.lookup("ecom.beans.account.AccountEntityFacade" + "_" + AccountEntityFacadeRemote.class.getName() + "@Remote");
            //out.println("Creation of accountEntityFacade...OK      ");
        } 
        catch (NamingException e)
        {
            out.println("Cannot get accountEntityFacade : " + e);
            System.exit(2);
        }
		
		try
		{
            addressEntityFacade = (AddressEntityFacadeRemote) initialContext.lookup("ecom.beans.address.AddressEntityFacade" + "_" + AddressEntityFacadeRemote.class.getName() + "@Remote");
            //out.println("Creation of addressEntityFacade...OK      ");
        }
		catch (NamingException e)
		{
            out.println("Cannot get addressEntityFacade : " + e);
            System.exit(2);
        }
		
		try
		{
            cartSessionBean = (CartSessionRemote) initialContext.lookup("ecom.beans.cart.CartSessionBean" + "_" + CartSessionRemote.class.getName() + "@Remote");
            //out.println("Creation of cartSessionBean...OK      ");
        } 
		catch (NamingException e)
		{
            out.println("Cannot get cartSessionBean : " + e);
            System.exit(2);
        }
		
		try
		{
            menuOrderEntityFacade = (MenuOrderEntityFacadeRemote) initialContext.lookup("ecom.beans.menuorder.MenuOrderEntityFacade" + "_" + MenuOrderEntityFacadeRemote.class.getName() + "@Remote");
            //out.println("Creation of menuOrderEntityFacade...OK     ");
        } 
		catch (NamingException e)
		{
            out.println("Cannot get menuOrderEntityFacade : " + e);
            System.exit(2);
        }
		
	
		       
		//traitement de send.
		//String st1 = request.getContextPath();
		//String st2 = request.getPathInfo();
		//String st3 = request.getServerName();
		//out.println(">>>>>>>>>>>"+st1+"<br>");
		//out.println(">>>>>>>>>>>"+st2+"<br>");
		//out.println(">>>>>>>>>>>"+st3+"<br>");
		
		String servletPath = request.getServletPath();
		if(servletPath.contains("/add")){
        	
        	String readCustomer = request.getParameter("readCustomer");
            //out.println("readCustomer = "+readCustomer);
            if(readCustomer !=	null)
            {
            	numChamp = 0 ;//initialisation
            	String firstname = request.getParameter("T"+numChamp++);
    			String lastname = request.getParameter("T"+numChamp++);
    			String tel = request.getParameter("T"+numChamp++);
    			String email = request.getParameter("T"+numChamp++);
    			String pwd = request.getParameter("T"+numChamp++);
    			String streetNum = request.getParameter("T"+numChamp++);
    			String streetName = request.getParameter("T"+numChamp++);
    			String zipcode = request.getParameter("T"+numChamp++);
    			String city = request.getParameter("T"+numChamp++);
    			String type_residence = request.getParameter("type_residence"); 
    			String buildingNum = request.getParameter("T"+numChamp++);
    			String floorNum = request.getParameter("T"+numChamp++);
    			String apartmentNum = request.getParameter("T"+numChamp++);
    			String iban = request.getParameter("T"+numChamp++);
    						
    			AddressEntity newAddress = registerAddress(streetNum ,streetName,zipcode,city,buildingNum,floorNum,apartmentNum,type_residence,1);		    
    			if(newAddress == null){
    		    	out.println("L'addresse n'a pas ete cree");
    		    }
    		    else
    		    {
    		    	//this.addressEntityFacade.addAddress(address, streetNum, streetName, buildingNum, floorNum, apartmentNum, zipcode, city)
    		    	
    		    	AccountEntity newAccount = registerAccount(1 , iban, accountEntityFacade );
    		    	if(newAccount == null){
    		    		out.println("Le compte banque n'a pas ete cree");
    		    	}
    		    	else
    		    	{	
    		    		//this.addressEntityFacade.persistAddress(newAddress);
    	    			//this.accountEntityFacade.persistAccount(newAccount);
    		    		//CustomerEntity newCustomer = registerCustomer(password, email, firstname, lastname, tel, newAddress, newAccount);
    	    			CustomerEntity newCustomer = this.customerEntityFacade.registerCustomer(pwd, email, firstname, lastname, tel, newAddress, newAccount);//.repersistCustomer(newCustomer);

    		    		if (newCustomer == null) 
    		    		{
    		    			out.println("Le compte client n'a pas ete cree");
    		    		} 
    		    		else 
    		    		{
    		    			out.println("<center>Compte client cree.<center>");
    		    		}
    		    	}
    		    }
    	    	        	
            }else{
            	 out.println("<form method=\"get\" action=\"\" name=\"form1\">");
            	 int numChamp1 = readCustomer( out , numChamp );
            	 int numChamp2 = readAddress(out , numChamp1);
            	 int numChamp3 = readAccount(out , numChamp2);
            	 out.println("<input type=\"submit\" value=\"readCustomer\" name=\"Envoyer\"><br>");
            	 out.println("</form>");
            }
            
            
        }
        else{
        	if( servletPath.contains("/product") ){
        		
        	}
        	else{
        		if(servletPath.contains("/cart") ){
        			
        		}
        		else{
        			if( servletPath.contains("/store") ){
        				        			}
        			else{
        				if( servletPath.contains("/checkout") ){
        					
        				}
        				else{//servletPath==orders
        					
        					
        				}
        				
        			}
        		}
        	}
        }
		


		
		
       
        out.println("</body>");
        out.println("</html>");
    }
}
